package com.rs.qm.modules.member.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.rs.qm.common.annotation.Log;
import com.rs.qm.common.utils.R;
import com.rs.qm.common.utils.RedisUtils;
import com.rs.qm.common.utils.StringUtil;
import com.rs.qm.modules.member.entity.FreeUserEntity;
import com.rs.qm.modules.member.entity.UserEntity;
import com.rs.qm.modules.member.service.UserService;
import com.rs.qm.modules.member.vo.LoginForm;
import com.rs.qm.modules.sys.service.SysUserTokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rs.qm.modules.member.service.FreeUserService;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 会员的登录与退出
 */
@RestController
public class LoginController {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private FreeUserService freeUserService;

    /**
     * 登录
     */
    @Log(value = "登录")
    @GetMapping("/pc/login/{telephone}")
    public R login(@PathVariable String telephone) throws IOException {
        Wrapper<FreeUserEntity> wrapper = new EntityWrapper<FreeUserEntity>();
        //设置查询条件
        wrapper.eq("mobile", telephone);
        FreeUserEntity freeUserEntity = freeUserService.selectOne(wrapper);
        if (freeUserEntity == null) {
            return R.error("该手机号尚未注册");
        }
        //生成token，并保存到数据库
        Map<String, Object> data = sysUserTokenService.createToken(freeUserEntity.getUserId());
        return R.okData(data);
    }

    /**
     * 退出
     */
    @GetMapping("/pc/logout")
    public R logout(HttpServletRequest request) {
        String token = getRequestToken((HttpServletRequest) request);
        if(!StringUtil.isEmpty(token)){
            redisUtils.delete(token);
        }
        return R.ok();
    }

    /**
     * 判断token是否有效
     *      看是否可以通过拦截器
     */
    @GetMapping("/pc/token/isvalid")
    public R isValidToken(){
        return R.ok();
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("token");

        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }

        return token;
    }
}
